﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CommonLib.LogOperation;
using CommonLib.SystemOperation;
using System.Reflection;
using WCFLib.Service;
using WCFLib.Host;
using CommonLib.CacheOperation;

namespace DevHost
{
    class Program
    {
        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();
            sw.Start();

            Logger.RegisterConsoleListener();

            StartService();

            Logger.Info(string.Format("启动完毕，耗时：{0}ms", sw.ElapsedMilliseconds));

            WaitingCommand();
        }

        private static void StartService()
        {
            var asm = Assembly.LoadFile(DirectoryHelper.GetAppRootDir() + "Contracts.dll");
            var lstServiceType = ServiceHelper.GetServiceType(asm);

            var dispatchAssemblyFilePath = DirectoryHelper.GetAppRootDir() + AppConfigCache.GetAppSettings("DispatchAssemblyName");

            foreach (var serviceType in lstServiceType)
            {
                try
                {
                    var hostService = new InterceptedWebServiceHost(serviceType, () =>
                    {
                        var assembly = Assembly.LoadFrom(dispatchAssemblyFilePath);
                        DispatchingCenter.Dispatch.Dispatcher.BuildDispatchRelationship(assembly);
                    });
                    hostService.Open();
                    Logger.Info("[" + serviceType.Name + "]启动成功...");
                }
                catch (Exception ex)
                {
                    Logger.Error("[" + (serviceType == null ? "null" : serviceType.Name) + "]启动异常：" + ex.ToString());
                    WaitingCommand();
                    return;
                }
            }
        }

        private static void WaitingCommand()
        {
            Console.WriteLine("R - 重启,E - 关闭");

            while (ResolveCommand(Console.ReadLine()))
            {

            }
        }

        private static bool ResolveCommand(string command)
        {
            switch (command.ToUpper())
            {
                case "R":
                    Process.Start(Application.ExecutablePath);
                    Environment.Exit(Environment.ExitCode);
                    break;
                case "E":
                    Environment.Exit(Environment.ExitCode);
                    break;
                default:
                    break;
            }

            return true;
        }
    }
}
